package com.wenson.behavior.memento;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: Editor
 * @Author: luowangcheng
 * @Date: 2024/6/16 8:26
 * @Description:
 */
public class Editor {
    private Doc doc;
    private List<History> historyRecords;//历史记录列表
    private int historyPosition = -1;//历史记录当前位置

    public Editor(Doc doc) {
        System.out.println("<<<打开文档" + doc.getTitle());
        this.doc = doc;
        historyRecords = new ArrayList<>();//初始化历史记录列表
        backup();
        show();
    }

    public void append(String txt) {
        System.out.println("<<<插入操作");
        doc.setBody(doc.getBody() + txt);
        backup();
        show();
    }

    public void delete() {
        System.out.println("<<<删除操作");
        doc.setBody("");
        backup();
        show();
    }

    private void backup() {
        historyRecords.add(doc.createHistory());
        historyPosition++;
    }

    public void save() {
        System.out.println("<<<存盘操作");
    }

    private void show() {
        System.out.println(doc.getBody());
        System.out.println("文档结束>>>\n");
    }

    public void undo() {
        System.out.println(">>>撤销操作");
        if (historyPosition == 0) {
            return;//到头了，不能再撤销
        }
        historyPosition--;
        History history = historyRecords.get(historyPosition);
        doc.restoreHistory(history);
        show();
    }

    public void redo() {
        System.out.println(">>>重做操作");
        if (historyPosition == historyRecords.size()-1){
            return;//到顶，不能再重做
        }
        historyPosition++;
        History history = historyRecords.get(historyPosition);
        doc.restoreHistory(history);
        show();
    }
}
